package by.yakusekmaxim.bookgid.services.impl;

import java.util.List;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import by.yakusekmaxim.bookgid.dataaccess.BookDao;
import by.yakusekmaxim.bookgid.dataaccess.GenreDao;
import by.yakusekmaxim.bookgid.datamodel.Book;
import by.yakusekmaxim.bookgid.datamodel.Book_;
import by.yakusekmaxim.bookgid.datamodel.Genre;
import by.yakusekmaxim.bookgid.services.GenreService;

@Service
public class GenreServiceImpl implements GenreService {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(GenreServiceImpl.class);

	@Inject
	private GenreDao dao;
	
	@Inject
	private BookDao daoBook;


	@Override
	public Genre get(Long id) {
		Genre entity = dao.getById(id);
		return entity;
	}

	@Override
	public void saveOrUpdate(Genre genre) {
		if (genre.getId() == null) {
			LOGGER.debug("Save new: {}", genre);
			dao.insert(genre);
		} else {
			LOGGER.debug("Update: {}", genre);
			dao.update(genre);
		}
	}

	@Override
	public void delete(Genre genre) {
		
		List<Book> bookList = daoBook.getAllBooks(Book_.genre,genre);
		if (bookList != null) {
			for (Book book : bookList) {
				book.setGenre(null);
				LOGGER.debug("Update: {}", book);
				daoBook.update(book);
			}
		}
		LOGGER.debug("Remove: {}", genre);
		dao.delete(genre.getId());

	}

	@Override
	public void deleteAll() {
		LOGGER.debug("Remove all Genres");
		dao.deleteAll();
	}

	@Override
	public List<Genre> getAll() {
		LOGGER.debug("Get all Genres");
		return dao.getAll();
	}

    @Override
    public Long getCount() {
        return dao.getCount();
    }
}
